package com.tunan.lsj.quartz;

import java.util.Calendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import com.tunan.common.constant.TokenConstant;
import com.tunan.persistence.model.TSysUserLoginTn;
import com.tunan.system.service.SysUserLoginService;
import com.tunan.system.service.TokenService;
import com.tunan.utils.RedisUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisException;

@Configuration
@EnableScheduling
public class RegularTask {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private RedisUtils redisUtils;

	@Autowired
	private TokenService tokenService;

	@Autowired
	private SysUserLoginService sysUserLoginService;

	/**
	 * 
	 * void
	 * 
	 * @Description 每天10分钟删除过期用户
	 * @date 2016年4月3日
	 * @author kinda
	 */
	@Scheduled(cron = "* */10 * * * ?")
	public void clearUserLoginTable() {
		try {
			sysUserLoginService.delByDeadline(Calendar.getInstance().getTime());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 
	 * void
	 * 
	 * @Description 每10分种检查一次REDIS服务器
	 * @date 2016年4月3日
	 * @author kinda
	 */
	@Scheduled(cron = "*/10 * * * * ?")
	public void checkRedis() {
		try {
			if ("PONG".equalsIgnoreCase(tokenService.redisLive())) {
				if (!redisUtils.isRedisLived()) {
					List<TSysUserLoginTn> userList = sysUserLoginService
							.selectByDeadline(Calendar.getInstance().getTime());
					Jedis jedis = redisUtils.getJedisPool().getResource();
					userList.parallelStream().forEach(m -> {
						if (!jedis.exists(m.getAccessToken() + "_")) {
							jedis.setex(m.getAccessToken(), TokenConstant.ACCESS_TOKEN_LIVE, m.getDlm());
							jedis.setex(m.getAccessToken() + "_", TokenConstant.FRESH_TOKEN_LIVE, m.getDlm());
						}
					});
					redisUtils.jedisClose(jedis);
					redisUtils.setRedisLived(true);
				}
			} else {
				redisUtils.setRedisLived(false);
			}
		} catch (JedisException e) {
			redisUtils.setRedisLived(false);
			if (logger.isDebugEnabled()) {
				logger.debug("{}-REDIS服务器不能连接", Calendar.getInstance());
			}
		}
	}
}